import time

from pyecharts import options as opts
from pyecharts.charts import Bar, Tab

from .user_tools import mat_avg

__all__ = ['time_analyse']


def time_analyse(emotion_kinds, emotion_list, time_data, mode=1):
    """
    对输入的情绪和时间数据，按小时进行统计，并输出各小时的平均情绪向量的条形图。

    :param emotion_kinds: 情绪种类，情绪向量各分量代表的情绪
    :param emotion_list: 情绪向量列表，emotion_analyse()的输出结果，参照emotion_analyse.py
    :param time_data: 时间数据，和情绪向量一一对应，格式为'%a %b %d %H:%M:%S +0800 %Y'
    :param mode: 情绪分析模式，参照emotion_analyse.py
    """

    # 组合时间和情绪数据
    time_list = [time.strptime(t, "%a %b %d %H:%M:%S +0800 %Y") for t in time_data]
    emotion_time = list(zip(emotion_list, time_list))

    # 统计各小时的情绪向量
    emotion_time_dict = dict()
    for elem in emotion_time:
        s = time.strftime('%H', elem[1])
        emotion_time_dict[s] = emotion_time_dict.get(s, []) + list(elem[0:1])

    # 计算各小时的平均情绪
    etd = emotion_time_dict.copy()  # 用于存储平均情绪
    for key in emotion_time_dict:
        etd[key] = mat_avg(etd[key])

    # 绘制条形图
    hour_data = sorted(etd.keys())
    emo_data = [etd[key] for key in hour_data]
    tab = Tab()
    for i in range(5):
        b = (
            Bar()
                .add_xaxis(hour_data)
                .add_yaxis(emotion_kinds[i], [elem[i] for elem in emo_data])
                .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
                .set_global_opts(
                yaxis_opts=opts.AxisOpts(
                    type_="value",
                    axistick_opts=opts.AxisTickOpts(is_show=True),
                ),
                tooltip_opts=opts.TooltipOpts(is_show=False),
                title_opts=opts.TitleOpts(title="{} 情绪-时间条形图".format(emotion_kinds[i])))
        )
        tab.add(b, emotion_kinds[i])
    tab.render(path="./output/time_analyse_{}.html".format(mode))
